<?php
require_once('../../../../wp-load.php');
require_once("/../includes/lib/openid.php");

const DOMAIN_NAME ="yourstyle.name";
const CALLBACK_URL ="http://yourstyle.name/raovat/";
$appId = "629757323723973";
$appSecrect = "84712023d7a767b9072ba9f7f3f2d90b";

// const URL_CONTROLLER = "http://yourstyle.name/yourstyle/raovat/?page_id=11";
// const IDPage = "11";
$isOk = false;
if(isset($_GET["provider"]) &&  !empty($_GET["provider"])){
	$provider = $_GET["provider"];
	$next = $_GET["next"];
	if(strcmp($provider, "GOOGLE")==0){
		$identify = 'https://www.google.com/accounts/o8/id';
		$isOk = true;
	}else if(strcmp($provider, "YAHOO")==0){
		$identify =  'https://me.yahoo.com';
		$isOk = true;
	}
}else{
	//co loi tra ve.
	//die();
}

if(isset($_GET["code"]) && !empty($_GET["code"])){
	$code = $_GET["code"];
	$state =$_GET["state"];
	$nextUrl = base64_decode($state);	
	$uri = get_template_directory_uri()."/controller/openId-controller.php";//?next=".$redirectTo."&provider=FACEBOOK";
	$uri = urlencode($uri);
	$token_url = "https://graph.facebook.com/oauth/access_token?client_id="+$appId+"&client_secret="+$appSecrect +"&code=".$code."&redirect_uri=".$uri;
	$response = @file_get_contents($token_url);
	$params = null;
	parse_str($response, $params);
	$graph_url = "https://graph.facebook.com/me?access_token=".$params['access_token'];
	$user = json_decode(file_get_contents($graph_url));
	$email = $user->email;
	$username = $user->username;
	
	$myrows = $wpdb->get_results( "SELECT *
					FROM ".$wpdb->users."
					WHERE user_email='".$email."'");

	if(sizeof($myrows) == 0){
		$dataEmail = explode("@", $email);
		$password = "yourstyle!@#".rand();
		$pass =md5($password);

		//insert user to database.
		$uid = wp_insert_user( array ('user_login' => $dataEmail[0],
				'display_name' => $username,
				'role' => 'Author',
				'user_email' => $email,
				'user_pass' => $password)) ;
	}
	else{
		$uid =$myrows[0]->ID;
		$username = $myrows[0]->user_login;
		$pass = $myrows[0]->user_pass;
	}
		
	$creds = array('user_login' => $username,
			'user_password' =>$pass,
			'remember' => true
	);
		
	// TODO do we deprecate the wp_authentication action?
	do_action_ref_array('wp_authenticate', array(&$creds['user_login'], &$creds['user_password']));
	$secure_cookie = apply_filters('secure_signon_cookie', $secure_cookie, $credentials);
		
	$user = wp_authenticate($creds['user_login'], $creds['user_password']);
	//wp_set_auth_cookie($user->ID, $credentials['remember'], $secure_cookie);
	wp_setcookie( $creds['user_login'], $creds['user_password'], true, "", "", true );

	echo "<script>
				self.close ();
				window.opener.location.href = '".$nextUrl."';
		</script>";
	$isOk = false;
}

if($isOk){
$openid = new LightOpenID(DOMAIN_NAME);
if(!$openid->mode) {
	$openid->identity = $identify;
	//$openid->returnUrl = $next;
	$openid->required = array('contact/email', 'pref/language', 'namePerson/friendly','namePerson', 'birthDate', 'person/gender');
	$urlOpenId = $openid->authUrl();
	wp_redirect($urlOpenId);
} elseif($openid->mode == 'cancel') {
	echo "<script>
					self.close ();
			</script>";

} else {
	if(isset($_GET["next"]) && !empty($_GET["next"])){
		$next = $_GET["next"];
	}else{
		$next = "http://yourstyle.name";
	}
	$userData = $openid->getAttributes();
	$username = "";
	$pass ="";
	//check user is exit or not
	$myrows = $wpdb->get_results( "SELECT *
					FROM ".$wpdb->users."
					WHERE user_email='".$userData['contact/email']."'");

	if(sizeof($myrows) == 0){
		$dataEmail = explode("@", $userData['contact/email']);
		$username = $dataEmail[0];
		$password = "yourstyle!@#".rand();
		$pass =md5($password);

		//insert user to database.
		$uid = wp_insert_user( array ('user_login' => $dataEmail[0],
				'display_name' => $userData['namePerson'],
				'user_email' => $userData['contact/email'],
				'user_pass' => $password)) ;
	}
	else{
		$uid =$myrows[0]->ID;
		$username = $myrows[0]->user_login;
		$pass = $myrows[0]->user_pass;
	}
		
	$creds = array('user_login' => $username,
			'user_password' =>$pass,
			'remember' => true
	);
		
	// TODO do we deprecate the wp_authentication action?
	do_action_ref_array('wp_authenticate', array(&$creds['user_login'], &$creds['user_password']));
	$secure_cookie = apply_filters('secure_signon_cookie', $secure_cookie, $credentials);
		
	$user = wp_authenticate($creds['user_login'], $creds['user_password']);
	//wp_set_auth_cookie($user->ID, $credentials['remember'], $secure_cookie);
	wp_setcookie( $creds['user_login'], $creds['user_password'], true, "", "", true );

	echo "<script>
				self.close ();
				window.opener.location.href = '".$next."';
		</script>";

	}
}
?>